import React from 'react';
import './departmentsManage.less';
import {browserHistory} from 'react-router';
import { Button, message,Collapse,Modal} from 'antd';
import ajax from '../../common/ajax';
import config from '../../config/config';
import $ from 'jquery';
const token = sessionStorage.getItem('token');
const allRouter=config.router;
const Panel = Collapse.Panel;
class DepartmentsManage extends React.Component {
    constructor(props){
        super(props);
        this.state={
            departmentsList:[],//科室列表
            hasDoctor:0,//删除科室确认该科室下是否有关联医生
        }
    }
    componentWillMount() {
    }
    componentDidMount() {
        //获取科室列表
        this.getDepartmentsList();
    }
    //获取科室列表
    getDepartmentsList() {
        let url=allRouter.patientOrigin+'/department/list';
        //console.log(url);
        $.ajax({
            url:url,
            type:'GET',
            headers: { Authorization: 'Bearer '+sessionStorage.getItem('token')},
            success:data=>{
                console.log(data);
                if(data.code===200){
                    //给列表每一项增加索引
                    if (data.department.length > 0) {
                        data.department.forEach((ele, i) => {
                            ele.index= i + 1;
                        });
                    }
                    this.setState({
                        departmentsList:data.department
                    },()=>{
                        console.log(this.state.departmentsList);
                    })
                }else{
                    console.log("获取科室列表列表出错");
                }
            },
            error:err=>{ console.log(err);}
        });
    }
    //下拉菜单改变监听函数
    handleChange(key){}
    //更改科室状态
    handleChangeState(id,state){
        let confirmString=<span></span>;
        console.log(id);
        if(state==='启用'){
            state='禁用'
        }else{
            state='启用'
        }
        let url=allRouter.patientOrigin+'/department/hasdoctors';
        $.ajax({
            url:url,
            type:'POST',
            headers: { Authorization: 'Bearer '+sessionStorage.getItem('token')},
            data:{
                id:id,
            },
            success:data=>{
                console.log(data);
                if(data.code===200){
                    let url=allRouter.patientOrigin+'/department/update';
                    $.ajax({
                        url:url,
                        type:'POST',
                        headers: { Authorization: 'Bearer '+sessionStorage.getItem('token')},
                        data:{
                            id:id,
                            state:state
                        },
                        success:data=>{
                            if(data.code===200){
                                message.info('更改科室状态成功',);
                                this.getDepartmentsList();
                            }else{
                                message.info('更改科室名称错误');
                            }
                        },
                        error:err=>{ console.log(err);}
                    });
                }else if(data.code===201){
                    confirmString=<span style={{color:'red'}}>该科室已关联医生，请先解除或更换关联关系</span>;
                    Modal.info({
                        title: '禁用科室',
                        content: confirmString,
                        onOk: () => {}
                    })
                }else{
                    message.info("更改科室状态出错，请重新操作。",1);
                }
            },
            error:err=>{ console.log(err);}
        });
    }
    //删除科室
    deleteDepartment(id){
        let confirmString=<span></span>;
        //获取该科室下有没有关联医生
        let url=allRouter.patientOrigin+'/department/hasdoctors';
        $.ajax({
            url:url,
            type:'POST',
            headers: { Authorization: 'Bearer '+sessionStorage.getItem('token')},
            data:{
                id:id,
            },
            success:data=>{
                console.log(data);
                if(data.code===200){
                    confirmString=<span>确认删除该科室吗</span>;
                    Modal.confirm({
                        title: '删除科室',
                        content: confirmString,
                        onCancel: () => { },
                        onOk: () => {
                            let url=allRouter.patientOrigin+'/department/delete';
                            $.ajax({
                                url:url,
                                type:'POST',
                                headers: { Authorization: 'Bearer '+token},
                                data:{
                                    id:id,
                                },
                                success:data=>{
                                    if(data.code===200){
                                        message.success('删除科室成功！', 2);
                                        this.getDepartmentsList();
                                    }else{
                                        message.error('删除科室失败，请重新尝试', 2);
                                    }
                                },
                                error:err=>{ console.log(err);}
                            });
                        }
                    })
                }else if(data.code===201){
                    confirmString=<span style={{color:'red'}}>该科室已关联医生，请先解除或更换关联关系</span>;
                    Modal.info({
                        title: '删除科室',
                        content: confirmString,
                        onOk: () => {}
                    })
                }else{
                    message.info("删除科室出错，请重新操作。",1);
                }
            },
            error:err=>{ console.log(err);}
        });
    }


    render(){
        return (
            <div className="container">
                <div className="departments-manage-content">
                    {/*增加按钮*/}
                    <div className="storeAdd  ">
                        <Button onClick={() => { browserHistory.push('addFirstDepartmentForm/0/0')}} type="primary">
                            <img src={require('../../../images/add.png')} alt=""/>新增一级科室</Button>
                    </div>
                    <div className="departments-manage-collapse" id="departments-collapse">
                        <Collapse onChange={this.handleChange.bind(this)}>
                            {
                                this.state.departmentsList.map((item,index)=>{
                                    let firstTitleHeader;
                                    if(this.state.departmentsList.length){
                                        if(!item.id){
                                            firstTitleHeader=<ul className="first-title-header my-clear-fix">
                                                <li>{item.name}</li>
                                                <li>
                                                    {/*<Button onClick={()=>{browserHistory.push('addFirstDepartmentForm/'+item._id+'/0')}}>增加科室</Button>*/}
                                                    <Button onClick={this.handleChangeState.bind(this,item._id,item.state)} type={item.state=='启用'?'primary':'danger'}>{item.state=='启用'?'已启用，点击禁用':'已禁用，点击启用'}</Button>
                                                    <Button  onClick={()=>{browserHistory.push('addFirstDepartmentForm/0/'+item._id)}} type="dashed">编辑</Button>
                                                    <Button  onClick={this.deleteDepartment.bind(this,item._id)} type="danger">删除</Button>
                                                </li>
                                            </ul>;
                                            return(
                                                <Panel header={firstTitleHeader} key={item._id}>
                                                    {
                                                        this.state.departmentsList.map((item1, index) => {
                                                            if (item1.id == item._id) {
                                                                return (<ul key={item1._id} className="my-clear-fix first-title-header second-title-header" >
                                                                    <li>{item1.name}</li>
                                                                    <li>
                                                                        <Button  onClick={this.handleChangeState.bind(this,item1._id,item1.state)} type={item1.state=='启用'?'primary':'danger'}>{item1.state=='启用'?'已启用，点击禁用':'已禁用，点击启用'}</Button>
                                                                        <Button  onClick={()=>{browserHistory.push('addFirstDepartmentForm/0/'+item1._id)}} type="dashed">编辑</Button>
                                                                        <Button  onClick={this.deleteDepartment.bind(this,item1._id)} type="danger">删除</Button>
                                                                    </li>
                                                                </ul>);
                                                            }
                                                        })
                                                    }
                                                </Panel>
                                            )
                                        }
                                    }
                                })
                            }
                        </Collapse>
                    </div>
                </div>
            </div>
        );
    }
}
export default DepartmentsManage;